package samsung.sds.survey.surveyStatistics.service.impl;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import samsung.sds.survey.surveyStatistics.dao.SurveyResultStatisticsMapper;
import samsung.sds.survey.surveyStatistics.model.QuestionEntity;
import samsung.sds.survey.surveyStatistics.model.QuestionOptionEntity;
import samsung.sds.survey.surveyStatistics.model.SurveyEntity;
import samsung.sds.survey.surveyStatistics.service.SurveyResultStatisticsService;
import samsung.sds.survey.surveyStatistics.util.SurveyStaticsUtils;
import samsung.sds.system.common.baseQuery.AbstractBaseService;

/**
 * @author HuangLong
 * @createDate 2016-01o-18
 * 
 * 统计已结束问卷结果业务层实现类
 */
@Service
public class SurveyResultStatisticsServiceImpl extends AbstractBaseService<SurveyEntity> implements SurveyResultStatisticsService{
	
	//转换统计百分比保留两位小数
	private DecimalFormat formatNumber = new DecimalFormat("##0.00");
	
    @Autowired
    private SurveyResultStatisticsMapper surveyResultStatisticsMapper;

    /**
     * 根据问卷surveyId查询问卷
     *
     * @param id 问卷surveyId
     * @return 问卷survey
     */
    public SurveyEntity findEntityById(String id) {
    	
        SurveyEntity survey = surveyResultStatisticsMapper.queryEntityById(id.toString());
        String surveyId = survey.getId();
        List<QuestionEntity> questions = this.getQeustionsBySurveyId(surveyId);
        
        for (int i = 0; i < questions.size(); i++) {
        	
            if (StringUtils.equals(questions.get(i).getQuestionType(), SurveyStaticsUtils.YN_TYPE)) {
            	
                List<QuestionOptionEntity> optionList = SurveyStaticsUtils.getYnTypeQuestionOptionEntities();
                questions.get(i).setQuestionOptionList(optionList);
            
            } else {
            	
                List<QuestionOptionEntity> optionList = this.getOptionsByQuestionId(questions.get(i).getId());
                
                questions.get(i).setQuestionOptionList(optionList);
            }
            
        }
        
        survey.setQuestion(questions);
        return survey;
    }

    /**
     * 根据问卷surveyId查询所有question
     *
     * @param surveyId 问卷surveyId
     * @return Question集合
     */
    public List<QuestionEntity> getQeustionsBySurveyId(String surveyId) {

        return this.getMapper().selectTF_F_QUESTION03(surveyId);
    }

    /**
     * 根据问题questionId查询所有option选项
     *
     * @param id 问题questionId
     * @return Question集合
     */
    public List<QuestionOptionEntity> getOptionsByQuestionId(String id) {

        return this.getMapper().selectTF_F_QUESTION_OPTIONITEMT(id);
    }

    private QuestionEntity getQualityCountPercent(QuestionEntity qEntity,int rangeCount){
            //将问题answer数字范围取出转为数组
            String[] rule = qEntity.getValidateRule().split(",");

            //取出最大值与最小值
            int min = Integer.parseInt(rule[0]);
            int max = Integer.parseInt(rule[1]);

            //将最大值与最小值划分为rangeCount个区间
            int avg = (max-min) / rangeCount;
            
            //新建选项option集合，用户存放划分的区间和区间投票数量与百分比
            List<QuestionOptionEntity> options2 = new ArrayList<QuestionOptionEntity>(rangeCount);
            for (int j = 0; j < rangeCount; j++) {
            	
            	options2.add(new QuestionOptionEntity());
			}

            //给问题添加rangeCount个区间范围
            for (int j = 0; j < rangeCount; j++) {
            	
            	if(j==0){
            		options2.get(j).setRule(min + "-" + (avg+min));
            	}else{
            		
            		if((min+avg*j+j) > max){
            			//在划分区间段时，超出区间范围的设置为无效区间
            			options2.get(j).setRule("无效区间");
            		}else{
            			options2.get(j).setRule(min+avg*j+j + "-" + ((min+avg*(j+1)+j)>max?max:(min+avg*(j+1)+j)));
            		}
            		
            	}
            	
			}

            //给5个区间设置投票数量
            for (int j = 0; j < rangeCount; j++) {
            	
            	if(!"无效区间".equals(options2.get(j).getRule())){
            		options2.get(j).setCount(this.getMapper().selectTF_F_SURVEY_RESULT02(qEntity.getSurveyId(),qEntity.getId(), Integer.parseInt(options2.get(j).getRule().split("-")[0]), Integer.parseInt(options2.get(j).getRule().split("-")[1])));
            	}else{
            		options2.get(j).setCount(0);
            	}
            }

            //五个区间总投票人数
            int allOptionTotal =0;
            for (int j = 0; j < rangeCount; j++) {
            	
            	allOptionTotal += options2.get(j).getCount();
            }
            
            //计算每个区间投票百分比
            for (int j = 0; j < options2.size(); j++) {
            	
            	if (options2.get(j).getCount() == 0) {
                    options2.get(j).setPercent("0.00%");
                } else {
                    options2.get(j).setPercent(formatNumber.format((float)options2.get(j).getCount() * 100 / allOptionTotal)+"%");
                }            	
            }
            for (QuestionOptionEntity option : options2) {
            	option.setWidth(option.getCount()>0? ((float) option.getCount()) / allOptionTotal + "" : "0.0");                
            }

            qEntity.setQuestionOptionList(options2);
            

         return qEntity;    
    }

    /**
     * 查询普通类型count数量与percent百分比
     *
     * @param questions Question集合
     * @param id        问卷surveyId
     * @return          Question集合
     */
    public List<QuestionEntity> getNormalCountPercent(
            List<QuestionEntity> questions, String id) {

        //遍历所有问题
        for (int i = 0; i < questions.size(); i++) {
        	
        	if("1".equals(questions.get(i).getQuestionType()) || "2".equals(questions.get(i).getQuestionType())){
        		
		            List<QuestionOptionEntity> optionList = questions.get(i).getQuestionOptionList();
		
		            int optionAllCount = 0;
		
		            //统计每个问题下的选项数量
		            for (int j = 0; j < optionList.size(); j++) {
		            	
		                optionList.get(j).setCount(this.getMapper().selectTF_F_SURVEY_RESULT03(id, optionList.get(j).getQuestionId(), optionList.get(j).getOptionValue()));
		                optionAllCount += optionList.get(j).getCount();
		            }
		
		            //统计每个问题下的选项百分比和宽度Width
		            if (optionAllCount != 0) {
		            	
		                for (int j = 0; j < optionList.size(); j++) {
		                	
		                    optionList.get(j).setPercent(formatNumber.format(((float)optionList.get(j).getCount() * 100) / optionAllCount) + "%");
		                    optionList.get(j).setWidth(((float) optionList.get(j).getCount()) / optionAllCount + "");
		                }
		                
		            } else {
		            	
		                for (int j = 0; j < optionList.size(); j++) {
		                	
		                    optionList.get(j).setPercent("0.00%");
		                    optionList.get(j).setWidth("0.0");
		                }
		                
		            }
		        }else if("6".equals(questions.get(i).getQuestionType())){
		        	QuestionEntity ynResult = getYNCountPercent(questions.get(i));
		        	questions.set(i,ynResult);
		        }else if("5".equals(questions.get(i).getQuestionType())){
		        	QuestionEntity qualityResult = 	getQualityCountPercent(questions.get(i),5);
		        	questions.set(i,qualityResult);
		        }
		        	
		        
		
		}
        return questions;
    }

    
    /**
     * 根据问卷surveyId查询数字类型对应所有question集合
     *
     * @param id 问卷surveyId
     * @return question集合
     */
    public List<QuestionEntity> queryQuestionAnswerCount(String id) {

        return this.getMapper().selectTF_F_SURVEY_RESULT01(id);
    }


    /**
     * 根据问卷id查询对应通用和YN类型问卷的所有问题question集合
     *
     * @param surveyid 问卷surveyId
     * @return question集合
     */
    public List<QuestionEntity> queryQuestionsBySurveyId(String surveyid) {

        return this.getMapper().selectTF_F_QUESTION01(surveyid);
    }
    
    /**
     * 获取SurveyResultStatisticsMapper
     */
    @Override
    protected SurveyResultStatisticsMapper getMapper() {

        return surveyResultStatisticsMapper;
    }

    /**
     * 查询组合统计所问卷投票所对应的用户
     *
     * @param map
     * @return
     */
    public List<String> queryUserSql(Map<String, String> map) {
        return surveyResultStatisticsMapper.selectTF_F_SURVEY_RESULT04(map);
    }

    /**
     * 查询每一个组合所对应的票数
     *
     * @param map
     * @return
     */
    public int queryVotedCountByPerGroupingStatics(Map<String, String> map) {
        return surveyResultStatisticsMapper.selectTF_F_SURVEY_RESULT05(map);
    }
    
    private QuestionEntity getYNCountPercent(QuestionEntity qEntity){
        //给YN类型问题添加两个选项0或1，和选项值是和否
        List<QuestionOptionEntity> optionList = new ArrayList<QuestionOptionEntity>(2);
        optionList.add(new QuestionOptionEntity());
        optionList.add(new QuestionOptionEntity());
        optionList.get(0).setOptionValue("1");
        optionList.get(0).setOptionName("Y");
        optionList.get(1).setOptionValue("0");
        optionList.get(1).setOptionName("N");

        //计算每个问题下的'是'和'否'数量
        int optionAllCount = 0;
        for (int j = 0; j < optionList.size(); j++) {
        	
            optionList.get(j).setCount(this.getMapper().selectTF_F_SURVEY_RESULT03(qEntity.getSurveyId(),qEntity.getId(), optionList.get(j).getOptionValue()));
            optionAllCount += optionList.get(j).getCount();
        }

        //计算每个问题下的是和否百分比和宽度Width
        if (optionAllCount != 0) {
        	
            for (int j = 0; j < optionList.size(); j++) {
            	
                optionList.get(j).setPercent(formatNumber.format((float)(optionList.get(j).getCount() * 100) / optionAllCount) + "%");
                optionList.get(j).setWidth(((float) optionList.get(j).getCount()) / optionAllCount + "");
            }
            
        } else {
        	
            for (int j = 0; j < optionList.size(); j++) {
            	
                optionList.get(j).setPercent("0.00%");
                optionList.get(j).setWidth("0.0");
            }
            
        }

        qEntity.setQuestionOptionList(optionList);
        return qEntity;
    
    }

}

